#include "thread_acceptdata.h"

thread_AcceptData::thread_AcceptData(QObject *parent) : QThread(parent)
{


    serialInit();

    connect(&serial,&QSerialPort::readyRead,this,&thread_AcceptData::onReadyRead);
   // qRegisterMetaType<QSerialPort::SerialPortError>("SerialPortError");
   // connect(&serial,&QSerialPort::breakEnabledChanged ,this,&thread_AcceptData::findPortClose);

}


void thread_AcceptData::serialInit()
{
    //获取串口号
   auto list = QSerialPortInfo::availablePorts();
   emit updateSerialPort(list);


}

/*void thread_AcceptData:: findPortClose()
{
    emit transferEmit();
}*/

void thread_AcceptData::onReadyRead()//读取数据
{
    data = serial.readAll();//auto
    qDebug() << "子线程 ：下位机传送过来的数据 :" << data;

    if(data.isEmpty())//判空
        return ;
    bufferData.append(data);
    qDebug() << bufferData.length();
    int locate = bufferData.indexOf('!');//找到帧尾
    if(-1 == locate)
    {
        return ;//数据包不对
    }

    QByteArray tmp = bufferData.mid(0,locate-1);//截取完整的信息帧 最后的 "&！"不要 所以最后一个字节是校验和

    emit completePack(tmp);
    bufferData = bufferData.mid(locate+1);
    while( bufferData.indexOf('!') != -1 )
    {
      locate = bufferData.indexOf('!');
      tmp = bufferData.mid(0,locate-1);
      emit completePack(tmp);
      bufferData = bufferData.mid(locate + 1);
    }
    buffer.clear();
    data.clear();
    bufferData.clear();

}


void thread_AcceptData::test()
{
    qDebug()<<"thread_Accepdata address"<<QThread::currentThread();

    int num = 0;
    while(1)
    {
        emit curNumber(num++);
        if(1000 == num)
        {
            break;
        }
        QThread::usleep(1);
    }
    qDebug()<<"test 执行完毕";
}

